﻿using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using ScpControl;
using System.Threading;
using System.IO;
using System.Net;

namespace ScpServer
{
    public partial class BetterDS4 : Form
    {
        int device = -1;    //Keeps track of which device is currently selected
        string devicesCache = "";   //Keeps a string of what devices are connected (kind of used like a checksum)

        public void RestartServer() {
            //Restart the server
            rootHub.Stop();

            Thread.Sleep(100);

            rootHub.Open();
            rootHub.Start();

            RefreshControllers();
        }

        public void RefreshControllers() {
            //Clear the controllers listbox
            lbxControllers.SelectedIndex = -1;
            lbxControllers.Items.Clear();

            //Populate the controllers listbox
            for (int Index = 0; Index < 4; Index++) {
                string s = rootHub.getControllerInfo(Index);
                if (s != null) {
                    lbxControllers.Items.Add("DS4 Controller " + (Index + 1) + (rootHub.PDS4Controllers[Index].IsUSB ? " (USB)" : " (Bluetooth)"));
                }
            }

        }

        public int IndexOfCI(System.Windows.Forms.ComboBox.ObjectCollection cbx, string s)
        {
            for (int i = 0; i < cbx.Count; i++)
            {
                if (cbx[i].ToString().ToUpper() == s.ToUpper())
                {
                    return i;
                }
            }
            return -1;
        }

        public void LoadForm(int d) {
            //Enable controls
            pgbBattery.Value = rootHub.PDS4Controllers[device].Charge;
            chkTouchPad.Checked = Global.getTouchEnabled(d);
            tbrSensitivity.Value = Global.getTouchSensitivity(d);
            radBatteryColor.Checked = Global.getLedAsBatteryIndicator(d);
            radPlayerColor.Checked = !radBatteryColor.Checked;
            chkFlashLED.Checked = Global.getFlashWhenLowBattery(d);
            nudBatteryWarning.Value = Global.getFlashPercentage(d);

            string[] files = { };

            if (Directory.Exists("Profiles"))
            {

                files = Directory.GetFiles("Profiles");

                for (int i = 0; i < files.Length; i++)
                {
                    files[i] = (files[i]).Replace(@"Profiles\", "").Replace(".ds4", "");
                }
            }
            else
            {
                Directory.CreateDirectory("Profiles");
            }

            cbxProfile.Items.Clear();
            cbxProfile.Items.AddRange(files);
            cbxProfile.SelectedIndex = IndexOfCI(cbxProfile.Items, Global.getProfile(device));

            cbxProfile.Enabled = true;
            btnNewProfile.Enabled = true;
            btnEditProfile.Enabled = true;
            btnDeleteProfile.Enabled = (cbxProfile.Items.Count > 1);
            chkTouchPad.Enabled = true;
            tbrSensitivity.Enabled = chkTouchPad.Checked;
            radPlayerColor.Enabled = true;
            radBatteryColor.Enabled = true;
            btnPlayerColor1.Enabled = true;
            btnPlayerColor2.Enabled = true;
            btnBatteryColor1.Enabled = true;
            btnBatteryColor2.Enabled = true;
            chkFlashLED.Enabled = true;
            nudBatteryWarning.Enabled = chkFlashLED.Checked;
        }

        public void DisableForm() {
            //Disable controls
            cbxProfile.Enabled = false;
            btnNewProfile.Enabled = false;
            btnEditProfile.Enabled = false;
            btnDeleteProfile.Enabled = false;
            chkTouchPad.Enabled = false;
            tbrSensitivity.Enabled = false;
            radBatteryColor.Enabled = false;
            radPlayerColor.Enabled = false;
            btnPlayerColor1.Enabled = false;
            btnPlayerColor2.Enabled = false;
            btnBatteryColor1.Enabled = false;
            btnBatteryColor2.Enabled = false;
            chkFlashLED.Enabled = false;
            nudBatteryWarning.Enabled = false;


            //Reset values to defaults
            pgbBattery.Value = 0;
            tbrSensitivity.Value = 100;
            nudBatteryWarning.Value = 20;

            //Clear the profile combo box
            cbxProfile.Items.Clear();

            //Uncheck checkboxes
            chkTouchPad.Checked = false;
            radPlayerColor.Checked = false;
            radBatteryColor.Checked = false;
            chkFlashLED.Checked = false;

        }

        

        public BetterDS4() {
            InitializeComponent();
        }

        private void BetterDS4_Load(object sender, EventArgs e) {
            Icon = Properties.Resources.Scp_All;
            tmrUpdate.Enabled = true;
            Global.Load();
            
            //Start the server
            rootHub.Open();
            rootHub.Start();
        }


        protected void tmrUpdate_Tick(object sender, EventArgs e) {
            
            //Check if any devices have changed states
            string s = "";
            for (int Index = 0; Index < 4; Index++) {
                if (rootHub.getControllerInfo(Index) != null) {
                    s += Index + (rootHub.PDS4Controllers[Index].IsUSB ? " (USB)" : " (Bluetooth)"); //Just use controller numbers + connection type. Ideally this would use some sort of unique ID to check if controllers have been switched
                }
            }

            //Update the device cache and refresh the controller list
            if (s != devicesCache) {
                devicesCache = s;
                RefreshControllers();
            }
        }

        private void BetterDS4_Close(object sender, FormClosingEventArgs e) {
            //Stop the server
            //rootHub.Stop();   //Stop logs the server shutdown
            rootHub.Close();    //Close does not*/
        }


        private void btnControlPanel_Click(object sender, EventArgs e) {
            //Open the "Game Controllers" panel in control panel
            System.Diagnostics.Process.Start("control.exe", "joy.cpl");
        }
        
        private void lbxControllers_SelectedIndexChanged(object sender, EventArgs e) {
            //Update the selected device variable
            device = lbxControllers.SelectedIndex;

            //Set the state of the form
            if (device == -1) {
                DisableForm();
            } else {
                LoadForm(device);
            }

        }

        private void chkTouchPad_CheckedChanged(object sender, EventArgs e) {
            if (chkTouchPad.Enabled) {
                //Enable the sensitivity trackbar
                Global.setTouchEnabled(device, chkTouchPad.Checked);
                rootHub.PDS4Controllers[device].isTouchEnabled = chkTouchPad.Checked;
                tbrSensitivity.Enabled = chkTouchPad.Checked;
            }
        }

        /*
        private void chkBatteryFlash_CheckedChanged(object sender, EventArgs e) {
            if (chkBatteryFlash.Enabled) {
                Global.setFlashWhenLowBattery(device, chkBatteryFlash.Checked);
            }
        }*/

        private void btnRefresh_Click(object sender, EventArgs e) {
            RestartServer();
        }

        /*private void tbrRumble_Scroll(object sender, EventArgs e) {
            if (tbrRumble.Enabled) {
                rootHub.setRumble(device, (byte)tbrRumble.Value, 0, 0);
            }
        }*/

        private void tbrSensitivity_Scroll(object sender, EventArgs e) {
            if (tbrSensitivity.Enabled) {
                Global.setTouchSensitivity(device, (byte)tbrSensitivity.Value);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e) {
            AboutBetterDS4 frmAbout = new AboutBetterDS4();
            frmAbout.Show();
        }
        
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e) {
            BetterDS4Options frmOptions = new BetterDS4Options();
            frmOptions.ShowDialog();
        }

        private void radPlayerColor_CheckedChanged(object sender, EventArgs e) {
            if (radPlayerColor.Enabled) {
                Global.setLedAsBatteryIndicator(device, !radPlayerColor.Checked);
            }
        }

        private void radBatteryColor_CheckedChanged(object sender, EventArgs e) {
            if (radBatteryColor.Enabled) {
                Global.setLedAsBatteryIndicator(device, radBatteryColor.Checked);
            }
        }

        private void btnPlayerColor1_Click(object sender, EventArgs e) {
            ColorDialog cd = new ColorDialog();
            ledColor ledc = Global.loadPlayerColor1(device);

            cd.Color = Color.FromArgb(ledc.red, ledc.green, ledc.blue);

            if (cd.ShowDialog() == DialogResult.OK) {
                Color c = cd.Color;

                Global.savePlayerColor1(device, c.R, c.G, c.B);

            }
        }

        private void btnPlayerColor2_Click(object sender, EventArgs e) {
            ColorDialog cd = new ColorDialog();
            ledColor ledc = Global.loadPlayerColor2(device);

            cd.Color = Color.FromArgb(ledc.red, ledc.green, ledc.blue);

            if (cd.ShowDialog() == DialogResult.OK) {
                Color c = cd.Color;

                Global.savePlayerColor2(device, c.R, c.G, c.B);
            }
        }

        private void btnBatteryColor1_Click(object sender, EventArgs e) {
            ColorDialog cd = new ColorDialog();
            ledColor ledc = Global.loadBatteryColor1(device);

            cd.Color = Color.FromArgb(ledc.red, ledc.green, ledc.blue);

            if (cd.ShowDialog() == DialogResult.OK) {
                Color c = cd.Color;

                Global.saveBatteryColor1(device, c.R, c.G, c.B);
            }
        }

        private void btnBatteryColor2_Click(object sender, EventArgs e) {
            ColorDialog cd = new ColorDialog();
            ledColor ledc = Global.loadBatteryColor2(device);

            cd.Color = Color.FromArgb(ledc.red, ledc.green, ledc.blue);

            if (cd.ShowDialog() == DialogResult.OK) {
                Color c = cd.Color;

                Global.saveBatteryColor2(device, c.R, c.G, c.B);
            }
        }

        private void chkFlashLED_CheckedChanged(object sender, EventArgs e) {
            if (chkFlashLED.Enabled) {
                Global.setFlashWhenLowBattery(device, chkFlashLED.Checked);
            }
            nudBatteryWarning.Enabled = chkFlashLED.Checked;
        }

        private void nudBatteryWarning_ValueChanged(object sender, EventArgs e) {
            if (nudBatteryWarning.Enabled) {
                Global.setFlashPercentage(device, (byte) nudBatteryWarning.Value);
            }
        }

        private void cbxProfile_SelectedIndexChanged(object sender, EventArgs e)
        {
            Global.setProfile(device, cbxProfile.Text);
        }

        private void btnNewProfile_Click(object sender, EventArgs e)
        {
            BetterDS4Mapper frmMapper = new BetterDS4Mapper(device, "");
            frmMapper.ShowDialog();
            LoadForm(device);
        }

        private void btnEditProfile_Click(object sender, EventArgs e)
        {
            BetterDS4Mapper frmMapper = new BetterDS4Mapper(device, cbxProfile.Text);
            frmMapper.ShowDialog();
            LoadForm(device);
        }

        private void btnDeleteProfile_Click(object sender, EventArgs e)
        {
            if (File.Exists(@"Profiles\" + cbxProfile.Text + ".ds4"))
            {
                File.Delete(@"Profiles\" + cbxProfile.Text + ".ds4");
                LoadForm(device);
                cbxProfile.SelectedIndex = 0;
            }
        }

        private void controlPanelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Open the "Game Controllers" panel in control panel
            System.Diagnostics.Process.Start("control.exe", "joy.cpl");
        }

        /*private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var webClient = new WebClient();
            string readHtml;
            try
            {
                readHtml = webClient.DownloadString("http://retardedlemon.com/betterds4/version.txt");
            }
            catch
            {
                readHtml = "";
            }

            if (readHtml != "")
            {
                if (Application.ProductVersion != readHtml)
                {
                    System.Diagnostics.Process.Start("http://retardedlemon.com/betterds4/BetterDS4-" + readHtml + ".zip");
                }
                else
                {
                    MessageBox.Show("You are already up to date");
                }
            }
            else
            {
                MessageBox.Show("An error occured while checking for updates. Visit http://retardedlemon.com/betterds4 to check manually.");
            }
        }*/
        
    }
}
